package com.jielihaofeng.springboot.sse.controller;

 import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Johnnie Wind
 * @description
 * @date 2021/6/11 16:10
 */
@Controller
@RequestMapping(path = "sse")
public class SseController {

    private static Map<String, SseEmitter> sseClientCache = new ConcurrentHashMap<>();

    @GetMapping(path = "")
    public String index() {
        return "index.html";
    }

    @ResponseBody
    @GetMapping(path = "subscribe", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    public SseEmitter push(String id) throws IOException {

        // 超时时间设置为3s，用于演示客户端自动重连
        SseEmitter sseEmitter = new SseEmitter(3_000L);

        // 设置前端的重试时间为1s
        sseEmitter.send(SseEmitter.event().reconnectTime(3000).data(id+"连接成功"));

        sseClientCache.put(id, sseEmitter);
        System.out.println("add " + id);

        sseEmitter.onTimeout(() -> {
            System.out.println(id + "超时");
            sseClientCache.remove(id);
        });

        sseEmitter.onCompletion(() -> System.out.println(id+"完成！！！"));
        return sseEmitter;
    }

//    @GetMapping(path = "subscribe")
//    public SseEmitter push(String id) {
//        // 超时时间设置为1小时
//        SseEmitter sseEmitter = new SseEmitter(3600_000L);
//        sseCache.put(id, sseEmitter);
//        sseEmitter.onTimeout(() -> sseCache.remove(id));
//        sseEmitter.onCompletion(() -> System.out.println("完成！！！"));
//        return sseEmitter;
//    }

    @GetMapping(path = "push")
    public String push(String id, String content) throws IOException {
        SseEmitter sseEmitter = sseClientCache.get(id);
        if (sseEmitter != null) {
            sseEmitter.send(content);
        }
        return "over";
    }

    @GetMapping(path = "over")
    public String over(String id) {
        SseEmitter sseEmitter = sseClientCache.get(id);
        if (sseEmitter != null) {
            sseEmitter.complete();
            sseClientCache.remove(id);
        }
        return "over";
    }

}
